<?php

namespace App\Http\Controllers\Entity\Tag;

use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\Tag\tagRequest;
use App\Models\Entity\sys_categories\sys_categories;
use App\Models\Entity\Tag\tag;
use App\Models\Entity\tag_content\tag_content;
use App\Repositories\Entity\Tag\tagRepository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use Validator;

class tagController extends Controller
{
    use ModelForm;

    /** @var  tagRepository */
    private $tagRepository;

    public function __construct(tagRepository $tagRepo)
    {
        $this->tagRepository = $tagRepo;
    }

    /**
     * Display a listing of the tag.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.tag.tags.index_header'));
            $content->description(__('entity.tag.tags.index_description'));
            $content->body($this->grid());
            Admin::script('addTagContent();');
            $content->row(view('entity.tag.addTagContent'));
        });
    }

    /**
     * Show the form for creating a new tag.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.tag.tags.create_header'));
            $content->description(__('entity.tag.tags.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created tag in storage.
     *
     * @param tagRequest $request
     *
     * @return Response
     */
    public function store(tagRequest $request)
    {
        $input = $request->all();

        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.icon');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $input['img'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        $tag = $this->tagRepository->create($input);

        Flash::success(__('entity.tag.tags.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.tag.tags.index'));

    }

    /**
     * Display the specified tag.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $tag = $this->tagRepository->findWithoutFail($id);

        if (empty($tag)) {
            Flash::error(__('entity.tag.tags.not_found'));

            return redirect(route('entity.tag.tags.index'));
        }

        return view('entity.tag.tags.show')->with('tag', $tag);

    }

    /**
     * Show the form for editing the specified tag.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.tag.tags.edit_header'));
            $content->description(__('entity.tag.tags.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified tag in storage.
     *
     * @param  int              $id
     * @param tagRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $tag = $this->tagRepository->findWithoutFail($id);

        if (empty($tag)) {
            Flash::error(__('entity.tag.tags.not_found'));

            return redirect(route('entity.tag.tags.index'));
        }
        $input = $request->all();
        $data  = [];
        if (array_key_exists('_file_del_', $input)) {
            $imgUrl       = $tag->img;
            $uploadConfig = config('custom.base.upload.icon');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $rootDir      = config('filesystems.disks.' . $driver . '.upload');
            if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                // $tag->img        = null;
                // $tag->deleted_at = null;
                // $tag = $this->tagRepository->update($input, $id);
                // $input['img'] = null;
                // $input['deleted_at'] = null;
                // $tag          = $this->tagRepository->update($input, $id);
                DB::table('tags')->where(['id' => $id])->update(['img' => null]);
                return response()->json(['message' => '图片删除成功!', 'status' => $flag]);
            }
            return response()->json(['message' => '图片删除失败!', 'status' => $flag]);
        }
        $sValidators = [
            'name'      => 'required|max:20',
            'tag_group' => 'required|max:100',
            'listorder' => 'required',
        ];
        $validators = [];

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($input, $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
            'name'      => '名称',
            'tag_group' => '标签组',
            'listorder' => '排序',
        ]
        );

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.icon');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath     = $rootDir . '/' . $dir . '/' . $newImageName;
                $input['img'] = $fullPath;
                $data['img']  = $fullPath;
                // 删除原先存储的图片
                $flag = Storage::disk($driver)->delete($tag->img);
                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $data['name']      = $request->input('name');
        $data['tag_group'] = $request->input('tag_group');
        $data['listorder'] = $request->input('listorder');
        $data['icon_type'] = $request->input('icon_type');
        $input['deleted_at'] = null;
        // dd($input);

        DB::table('tags')->where(['id' => $id])->update($data);
        // $tag = $this->tagRepository->update($input, $id);

        Flash::success(__('entity.tag.tags.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.tag.tags.index'));
    }

    /**
     * Remove the specified tag from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->tagRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('entity.tag.tags.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $tag = $this->tagRepository->findWithoutFail($id);

        if (empty($tag)) {
            Flash::error(__('entity.tag.tags.not_found'));

            return redirect(route('entity.tag.tags.index'));
        }

        if ($flag = $this->tagRepository->delete($id)) {

            return response()->json(['message' => __('entity.tag.tags.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(tag::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '标签名称');
            $tagGroups = sys_categories::orderBy('listorder', 'asc')->pluck('title', 'id');
            $form->select('tag_group', '标签组')->options($tagGroups);
            $form->textarea('description', '描述');
            $form->number('listorder', '排序');

            $form->radio('icon_type', 'icon类型')->options(
                [
                    '1' => '图片',
                    '2' => '文件',
                ]
            )->default('1');
            $form->image('img', 'icon')->removable();

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

            $form->saving(function (Form $form) {

                $error = new MessageBag([
                    'title'   => 'title...',
                    'message' => 'message....',
                ]);

                return back()->with(compact('error'));

            });

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(tag::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('entity.tag.tags.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('entity.tag.tags.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('entity.tag.tags.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('entity.tag.tags.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('entity.tag.tags.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('entity.tag.tags.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('entity.tag.tags.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.tag.tags.destroy')) {
                    $actions->disableDelete();
                }

                // append一个操作
                $actions->prepend('<a href="' . $actions->getKey() . '/content"><i class="fa fa-list" title="媒资列表"></i></a>');
                // append一个操作
                $actions->append('<a class="add-subcolumn-asset" href="javascript:void(0);" tag_id="' . $actions->getKey() . '"><i class="fa fa-paper-plane" title="贴标签"></i></a>');
            });

            // 导出按钮
            if (Admin::user()->cannot('entity.tag.tags.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.tag.tags.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('name', '标签名称')->sortable();
            $grid->column('tagGroup.title', '标签组')->sortable();
            $grid->column('description', '描述')->sortable();
            $uploadConfig = config('custom.base.upload.icon');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            $grid->column('icon_type', 'icon类型')->display(function ($val) {
                $name = '图片';
                if ($val == '2') {
                    $name = '文件';
                }
                return '<span class="badge bg-green">' . $name . '</span>';
            });
            $grid->column('img', 'icon')->image($host);

            $grid->column('listorder', '排序')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '标签名称');
                $options = array(); $filter->in('tag_group', '标签组')->select($options);
                $filter->between('created_at', '创建时间')->datetime();

            });
        });
    }

    /*
     * 标签内容管理页面
     */
    public function content(Request $request, $id)
    {
        //return response()->json(['status' => 'error', 'content' => '非法操作1']);
        $taginfo = tag::find($id);
        return Admin::content(function (Content $content) use ($id, $taginfo) {
            $content->header(__('内容标签管理'));
            $content->description(__('标签名称【' . $taginfo['name'] . "】 " . $taginfo['description']));
            Admin::script('entityTagContentAsset();');
            $content->row(view('entity.tag.tagContent', ['tag_id' => $id]));
            Admin::script('addTagContent();');
            $content->row(view('entity.tag.addTagContent'));
        });

    }

    public function selectTag(Request $request)
    {
        $sys_categories = new sys_categories();
        $tag_groups     = $sys_categories->tagGroup(false);

        $tag_content_type = addslashes(tag_content::$tag_content_type[$request->get('tag_content_type')]);

        $viewData = array(
            'tag_groups'       => json_decode($tag_groups, true),
            'tag_content_id'   => $request->get('tag_content_id'),
            'tag_content_type' => $tag_content_type,
        );
        return view('entity.tag.addContentTag', $viewData);
    }

    public function queryList(Request $request)
    {

        // 搜索框的值
        $search_value = $request->input('search_value');
        // 收费类型
        $tag_group = $request->input('tag_group');

        $data         = array();
        $data['draw'] = $request->get('draw');
        $start        = $request->get('start') ?: 0;
        $length       = $request->get('length') ?: 10;
        $order        = $request->get('order');
        $columns      = $request->get('columns');
        $search       = $request->get('search');

        $model_tag = new tag();
        $where     = array();
        if (!empty($tag_group)) {
            $where[] = array('tag_group', '=', $tag_group);
        }
        if (!empty($search_value)) {
            $where[] = array('name', 'like', '%' . $search_value . '%');
        }

        if ($order) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }
        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        list($data['recordsTotal'], $data['recordsFiltered'], $data['data']) = $model_tag->tagList($where, $start, $length, $ord);
        return response()->json($data);
    }

}
